package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/admin/auth")
@Slf4j
public class AdminAuthController {


    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        log.debug("退出成功");
        return ResponseUtil.ok();
    }

    /**
     * 登录后获取 用户的基本信息的
     * @return
     */
    @RequestMapping("/info")
    public Object info(){
        log.debug("登录后获取 用户的基本信息的");
        //当前用户对象
        Subject currentUser = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) currentUser.getPrincipal();
        String username = admin.getUsername();
        String avatar = admin.getAvatar();

        Map<String,Object> data = new HashMap<>();
        data.put("name", username);
        data.put("avatar", avatar);

        Integer[] roleIds = admin.getRoleIds();

        Set<String> roles = roleService.findRolesByIds(roleIds);
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);

        data.put("roles", roles);
        data.put("perms", perms);
        return ResponseUtil.ok(data);

    }

    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map){
        String code = map.get("code");
        String username = map.get("username");
        String password = map.get("password");
        String uuid = map.get("uuid");

        if(StringUtils.isEmpty(uuid) ||StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(username) ||StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument() ;
        }
        //校验验证码
        String captcha = CaptchaCodeManager.getCachedCaptcha(uuid);

        if(captcha == null){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }

        if( ! code.equalsIgnoreCase(captcha)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }


        UsernamePasswordToken token = new UsernamePasswordToken(username, password);


        //登录
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            System.out.println(subject.isAuthenticated());
            System.out.println(subject.hasRole("超级管理员") ? "是超级管理员": "不是超级管理员");
            System.out.println(subject.isPermitted("admin:category:update") ? "有权限": "没有权限");

            return ResponseUtil.ok(subject.getSession().getId());
        } catch (UnknownAccountException e){
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        } catch (LockedAccountException e){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);
        }
         catch (Exception e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }
    }

    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        //生成一个5位的验证码
        String code = VerifyCodeUtils.generateVerifyCode(5);
        //生成一个uuid
        String uuid = UUID.randomUUID().toString();
        //添加验证码到缓存， 方便后期 登录校验验证码
        boolean isSuccess = CaptchaCodeManager.addToCache(uuid, code, 10);
        //判断是否成功
        if(!isSuccess){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_FREQUENCY);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成 图片
        VerifyCodeUtils.outputImage(111, 36, outputStream, code);
        //拼接 下行参数 的格式
        Map<String ,Object> data = new HashMap<>();
        data.put("uuid", uuid);
        data.put("img", Base64.encode(outputStream.toByteArray()));

        return ResponseUtil.ok(data);
    }

}
